<?php
/**
 * Created by PhpStorm.
 * User: adophper
 * Date: 2018-03-20
 * Time: 17:09
 */
namespace frontend\controllers;

use common\helpers\TStringHelper;
use common\models\Exhibition;
use common\models\Region;
use common\models\User;
use common\models\UserFollow;
use common\services\ExhibitionAudienceServices;
use common\services\ExhibitionBusinessServices;
use common\services\ExhibitionExhibitorServices;
use common\services\ExhibitionMeetingServices;
use common\services\ExhibitionPictureServices;
use common\services\UserFollowServices;
use common\services\UserMeetingServices;
use Yii;
use common\models\UserHistory;
use common\services\ExhibitionCategoryServices;
use common\services\ExhibitionServices;
use common\services\RegionServices;
use common\services\UserHistoryServices;
use frontend\base\BaseFrontController;
use yii\db\mssql\PDO;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class ZhanhuiController extends BaseFrontController
{
    /**
     * 展会首页
     * @return string
     */
    public function actionIndex()
    {
        $params = Yii::$app->request->queryParams;
        if (!isset($params['starttime'])) {
            $params['starttime'] = date('Y-m-d');
        }
        if (!isset($params['endtime'])) {
            $params['endtime'] = '';
        }
        if (!isset($params['category_id'])) {
            $params['category_id'] = '';
        }
        if (!isset($params['category_name'])) {
            $params['category_name'] = '';
        }
        if (!isset($params['city'])) {
//            $city = TStringHelper::getClientCity();
            $city = '';
            $params['city'] = $city;
            if (!empty($city)) {
                $find = Region::find(false)->andFilterWhere(['=', 'status', Region::STATUS_FLAG_NORMAL])->andFilterWhere(['like', 'name', $city])->asArray()->select('id,name')->one();
                if (!empty($find)) {
                    $params['city_arr'] = urlencode(json_encode(array(array('id' => $find['id'], 'name' => $find['name']))));
                }
            }
        }
        if (!isset($params['city_arr'])) {
            $params['city_arr'] = '';
        }
        if (!isset($params['keywords'])) {
            $params['keywords'] = '';
        }
        if (!isset($params['order'])) {
            $params['order'] = '';
        }
        if (!isset($params['sort'])) {
            $params['sort'] = 'DESC';
        }
        if (!isset($params['type'])) {
            $params['type'] = 'icon';
        }
        if (!isset($params['over'])) {
            $params['over'] = 0;
        }
        //展会列表
        $exhibitionService = new ExhibitionServices();
        $params['defaultPageSize'] = 12;
        $exhibition = $exhibitionService->searchPage($params);
        //你可能感兴趣的展会
        $userId = '';
        if (!Yii::$app->user->getIsGuest()) {
            $userId = Yii::$app->user->getId();
        }
        $related = $exhibitionService->getUserInterestByUserId($userId);
        $compareData = $exhibitionService->getCompareExhibition();

        return $this->render('index', [
            'data' => $exhibition,
            'params' => $params,
            'related' => $related,
            'compareData' => $compareData['data'],
        ]);
    }

    /**
     * 展会详情
     * @param $id
     * @return string
     */
    public function actionDetail($id){
        $service = new ExhibitionServices();
        $data = $service->getDetail($id);
        //添加浏览记录
        $historyService = new UserHistoryServices();
        $userId = '';
        if (!Yii::$app->user->getIsGuest()) {
            $userId = Yii::$app->user->getId();
        }
        $historyService->addRecord(UserHistory::USER_HISTORY_TYPE_EXHIBITION, $id, $userId);

        //同期会议
        $meetingService = new ExhibitionMeetingServices();
        $meeting = $meetingService->getExhibitionMeeting($id);
        $meetingOver = false;
        if (!empty($meeting->starttime)) {
            $meetingOver = strtotime($meeting->starttime) < time() ? true : false;
        }
        //判断是否登记过会议提醒
        $userMeetingService = new UserMeetingServices();
        $hasRegisterMeeting = $userMeetingService->hasUserMeetingData($userId, $meeting->id);
        //知名展商
        $exhibitionExhubitorService = new ExhibitionExhibitorServices();
        $exhibitor = $exhibitionExhubitorService->getExhibitorsByExhibitionId($id);
        //图片
        $pictureService = new ExhibitionPictureServices();
        $picture = $pictureService->getExhibitionPictureByEid($id);
        //同期展会
        //$same = $service->getSameExhibition($id);
        $compareData = $service->getCompareExhibition();

        //参展商构成
        $businessService = new ExhibitionBusinessServices();
        $businessData = $businessService->getExhibitionBusiness($id);
        //专业观众数量
        $audienceService = new ExhibitionAudienceServices();
        $audienceData = $audienceService->getExhibitionAudience($id);

        return $this->render('detail', [
            'data' => $data,
            'model' => $data['model'],
            'meeting' => $meeting,
            'meetingOver' => $meetingOver,
            'hasRegisterMeeting' => $hasRegisterMeeting,
            'exhibitor' => $exhibitor,
            'picture' => $picture,
            'compareData' => $compareData['data'],
            'businessData' => $businessData,
            'audienceData' => $audienceData,
        ]);
    }

    /**
     * 获取行业分类
     * @return string
     */
    public function actionGetCategory(){
        $categoryId = Yii::$app->request->get('category_id');
        $categoryService = new ExhibitionCategoryServices();
        $category = $categoryService->getIndexCategory();

        return $this->renderAjax('category', [
            'category' => $category,
            'categoryId' => $categoryId,
        ]);
    }

    /**
     * 获取城市
     * @return string
     */
    public function actionGetCity(){
        $pid = Yii::$app->request->get('pid');
        if (empty($pid)) $pid = 0;
        $regionService = new RegionServices();
        //$data = $regionService->getRegion($pid);
        $city_arr = Yii::$app->request->get('city_arr');
        $hotData = $regionService->getRegionHot();
        $data = $regionService->getRegionByPinyin();

        return $this->renderAjax('city', [
            'hot' => $hotData,
            'data' => $data,
            'pid' => $pid,
            'city_arr' => !empty($city_arr) ? json_decode(urldecode($city_arr), true) : null,
        ]);
    }

    /**
     * 添加关注
     * @return array
     */
    public function actionGoFollow(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->post('id');
        if (empty($id)) {
            return ['code' => -1, 'data' => [], 'msg' => '参数错误'];
        }
        //$userId = Yii::$app->request->post('userId');
        $userId = Yii::$app->user->getId();
        if (empty($userId)) {
            return ['code' => -1, 'data' => [], 'msg' => '未登录'];
        }
        $model = Exhibition::findOne($id);
        if (empty($model)) {
            return ['code' => -1, 'data' => [], 'msg' => '数据不存在'];
        }
        $userFollowService = new UserFollowServices();
        $result = $userFollowService->goFollow($userId, UserFollow::USER_FOLLOW_TYPE_EXHIBITION, $id);
        if ($result !== false) {
            $callback = ['code' => 0, 'data' => [], 'msg' => '操作成功'];
        }else{
            $callback = ['code' => -1, 'data' => [], 'msg' => '操作失败'];
        }
        return $callback;
    }

    /**
     * 展商构成饼图
     * @param $exhibition_id
     * @return string
     */
    public function actionGetBusiness($exhibition_id){
        $businessService = new ExhibitionBusinessServices();
        $data = $businessService->getExhibitionBusiness($exhibition_id);
        //排序
        $color = [];
        $label = [];
        $value = [];
        if (!empty($data)) {
            ArrayHelper::multisort($data, 'num', SORT_DESC);
            $allColor = TStringHelper::getColor();
            foreach ($data as $key => $val) {
                $color[] = $allColor[$key];
                $label[] = $val['title'];
                $value[] = $val['num'];
            }
        }

        return $this->renderAjax('get-chart', [
            'label' => $label,
            'value' => $value,
            'color' => $color,
            'div' => 'business_ctx',
        ]);
    }

    /**
     * 观众构成饼图
     * @param $exhibition_id
     * @return string
     */
    public function actionGetAudience($exhibition_id){
        $audienceService = new ExhibitionAudienceServices();
        $data = $audienceService->getExhibitionAudience($exhibition_id);
        //排序
        $color = [];
        $label = [];
        $value = [];
        if (!empty($data)) {
            ArrayHelper::multisort($data, 'num', SORT_DESC);
            $allColor = TStringHelper::getColor();
            foreach ($data as $key => $val) {
                $color[] = $allColor[$key];
                $label[] = $val['title'];
                $value[] = $val['num'];
            }
        }

        return $this->renderAjax('get-chart', [
            'label' => $label,
            'value' => $value,
            'color' => $color,
            'div' => 'audience_ctx',
        ]);
    }

    /**
     * 添加用户会议提醒功能
     * @return array
     */
    public function actionUserMeeting() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $exhibition_id = Yii::$app->request->post('exhibition_id');
        $meeting_id = Yii::$app->request->post('meeting_id');
        $userId = Yii::$app->user->getId();
        if (empty($userId)) {
            return ['code' => -1, 'data' => [], 'msg' => '请登录'];
        }
        if (empty($exhibition_id) || empty($meeting_id)) {
            return ['code' => -2, 'data' => [], 'msg' => '网络错误'];
        }
        $userMeetingService = new UserMeetingServices();
        $result = $userMeetingService->userInsertMeeting($userId, $exhibition_id, $meeting_id);
        return $result;
    }

    /**
     * 展会对比页面展示
     * @return string
     */
    public function actionCompare(){
        $service = new ExhibitionServices();
        $data = $service->getCompareData();

        return $this->render('compare', [
            'data' => $data,
        ]);
    }

    /**
     * 展会对比处理
     * @return array
     */
    public function actionCompareData(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $id = Yii::$app->request->post('id');
        $service = new ExhibitionServices();
        if (!empty($id)) {
            $result = $service->addCompareExhibition($id);
        }else{
            $result = $service->getCompareExhibition();
        }

        return $result;
    }

    /**
     * 清除对比数据
     * @return array
     */
    public function actionRemoveCompare(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $service = new ExhibitionServices();
        $service->removeCompareExhibition();

        return ['code' => 0, 'data' => [], 'msg' => 'ok'];
    }

}